package study.doc.word.support;

import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMath;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMathPara;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTR;

@Slf4j
public class OoxmlUtils {

    /**
     * @param omml
     * @return CTOMath
     */
    public static CTOMath getOMML(String omml) {
        CTOMath ctOMath;
        try {
            CTOMathPara ctOMathPara = CTOMathPara.Factory.parse(omml);
            int size = ctOMathPara.sizeOfOMathArray();
            if (size == 0) {
                log.warn("{}", omml);
                return null;
            }
            ctOMath = ctOMathPara.getOMathArray(0);
            //for making this to work with Office 2007 Word also, special font settings are necessary
            XmlCursor xmlcursor = ctOMath.newCursor();
            while (xmlcursor.hasNextToken()) {
                XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
                if (tokentype.isStart()) {
                    if (xmlcursor.getObject() instanceof CTR) {
                        CTR cTR = (CTR) xmlcursor.getObject();
                        cTR.addNewRPr2().addNewRFonts().setAscii("Cambria Math");
                        cTR.getRPr2().getRFonts().setHAnsi("Cambria Math");
                    }
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }
        return ctOMath;
    }
}
